package com.momo.mal.util;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import net.momo.mal.R;
import com.momo.mal.database.MalDatabaseAdapter;
import com.momo.mal.entity.Anime;
import com.momo.mal.entity.History;
import com.momo.mal.entity.Manga;
import com.momo.mal.entity.Related;
import com.momo.mal.util.AnimeUtil.RequestAnimeUpdate;


import org.apache.commons.lang3.text.WordUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.cookie.DateParseException;
import org.apache.http.impl.cookie.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MangaUtil {
	public static String parsingReadStatus(String status) {
		if(status.equals("reading")) return "reading";
		else if(status.equals("completed")) return "completed";
		else if(status.equals("on-hold")) return "onhold";
		else if(status.equals("dropped")) return "dropped";
		else return "plantoread";
	}
	
	public static String parsingReadStatusView(String status) {
		if(status.equals("reading")) return "Reading";
		else if(status.equals("completed")) return "Completed";
		else if(status.equals("onhold")) return "On-hold";
		else if(status.equals("dropped")) return "Dropped";
		else return "Plan to Read";
	}
	
	public static Manga parsingMangaFromJson(JSONObject json) {
		Manga manga = new Manga();
		
		try {
			manga.setId(json.getString("id"));
			manga.setTitle(json.getString("title"));
			manga.setType(json.getString("type"));
			manga.setChapters(json.getString("chapters") == "null" ? "0" : json.getString("chapters"));
			manga.setVolumes(json.getString("volumes") == "null" ? "0" : json.getString("volumes"));
			manga.setStatus(json.getString("status"));
			manga.setRank(json.getString("rank"));
			manga.setSynopsis(json.getString("synopsis"));
			manga.setImageUrl(json.getString("image_url"));
			
			String parsingGenre = json.getString("genres").replace("[", "")
					.replace("]", "").replace("\"", "").replace(",", ", ");
			manga.setGenres(parsingGenre);
			
			DecimalFormat formatterScore = new DecimalFormat("##.00");
			DecimalFormat formatter = new DecimalFormat("#,###");
			manga.setMemberScore(formatterScore.format(Double.parseDouble(json.getString("members_score"))));
			manga.setMemberCount(formatter.format(Double.parseDouble(json.getString("members_count"))));
			manga.setFavoriteCount(formatter.format(Double.parseDouble(json.getString("favorited_count"))));
			manga.setPopularityRank(json.getString("popularity_rank"));

			JSONObject jsonTitleAlternative = json.getJSONObject("other_titles");
			String synonyms = "";
			String english = "";
			String japanese = "";
			if (jsonTitleAlternative.has("english") == true) {
				english = jsonTitleAlternative.getString("english").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}
			if (jsonTitleAlternative.has("synonyms") == true) {
				synonyms = jsonTitleAlternative.getString("synonyms").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}
			if (jsonTitleAlternative.has("japanese") == true) {
				japanese = jsonTitleAlternative.getString("japanese").replace("[", "")
						.replace("]", "").replace("\"", "").replace(",", ", ");
			}
			
			manga.setEnglish(english);
			manga.setSynonyms(synonyms);
			manga.setJapanese(japanese);
					
			List<Related> relations = new ArrayList<Related>();
			Related related = new Related();
			
			int a = 0;
			JSONArray jsonArrayAnimeAdaptation = json.getJSONArray("anime_adaptations");
			if(jsonArrayAnimeAdaptation.length() > 0) {
				for (a = 0; a < jsonArrayAnimeAdaptation.length(); a++) {
					manga.setAnimeAdaptation("has");
					JSONObject jsonObject2 = jsonArrayAnimeAdaptation.getJSONObject(a);
					
					related = new Related();
					related.setRelatedId(jsonObject2.getString("anime_id"));
					related.setType("adaptations");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(0);
					
					relations.add(related);
				}
			} else {
				manga.setAnimeAdaptation("");
			}
			
			JSONArray jsonArrayRelatedManga = json.getJSONArray("related_manga");
			if(jsonArrayRelatedManga.length() > 0) {
				for (a = 0; a < jsonArrayRelatedManga.length(); a++) {
					manga.setRelatedManga("has");
					JSONObject jsonObject2 = jsonArrayRelatedManga.getJSONObject(a);
					
					related = new Related();
					related.setRelatedId(jsonObject2.getString("manga_id"));
					related.setType("related_manga");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(0);
					
					relations.add(related);
				}
			} else {
				manga.setRelatedManga("");
			}
			
			JSONArray jsonArrayAlternative = json.getJSONArray("alternative_versions");
			if(jsonArrayAlternative.length() > 0) {
				for (a = 0; a < jsonArrayAlternative.length(); a++) {
					manga.setAlternative("has");
					JSONObject jsonObject2 = jsonArrayAlternative.getJSONObject(a);
					
					related = new Related();
					related.setRelatedId(jsonObject2.getString("manga_id"));
					related.setType("alternative_versions");
					related.setMasterId(json.getString("id"));
					related.setTitle(jsonObject2.getString("title"));
					related.setAnime(0);
					
					relations.add(related);
				}
			} else {
				manga.setAlternative("");
			}
			
			manga.setRelated(relations);
			
//			StringBuffer bufferAnimeAdaptation = new StringBuffer(0);
//			JSONArray jsonArrayAnimeAdaptation = json.getJSONArray("anime_adaptations");
//			for(a = 0; a < jsonArrayAnimeAdaptation.length(); a++) {
//				JSONObject jsonObject = jsonArrayAnimeAdaptation.getJSONObject(a);
//				if (a == 0) {
//					bufferAnimeAdaptation.append(jsonObject.getString("title"));
//				} else {
//					bufferAnimeAdaptation.append(", ").append(
//							jsonObject.getString("title"));
//				}
//			}
//			manga.setAnimeAdaptation(bufferAnimeAdaptation.toString());
//			
//			StringBuffer bufferRelatedManga = new StringBuffer(0);
//			JSONArray jsonArrayRelatedManga = json.getJSONArray("related_manga");
//			for(a = 0; a < jsonArrayRelatedManga.length(); a++) {
//				JSONObject jsonObject = jsonArrayRelatedManga.getJSONObject(a);
//				if (a == 0) {
//					bufferRelatedManga.append(jsonObject.getString("title"));
//				} else {
//					bufferRelatedManga.append(", ").append(
//							jsonObject.getString("title"));
//				}
//			}
//			manga.setRelatedManga(bufferRelatedManga.toString());
//			
//			StringBuffer bufferAlternative = new StringBuffer(0);
//			JSONArray jsonArrayAlternative = json.getJSONArray("alternative_versions");
//			for(a = 0; a < jsonArrayAlternative.length(); a++) {
//				JSONObject jsonObject = jsonArrayAlternative.getJSONObject(a);
//				if (a == 0) {
//					bufferAlternative.append(jsonObject.getString("title"));
//				} else {
//					bufferAlternative.append(", ").append(
//							jsonObject.getString("title"));
//				}
//			}
//			manga.setAlternative(bufferAlternative.toString());
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return manga;
	}
	
	@SuppressWarnings("deprecation")
	public static void mangaAddOrUpdatePopUp(final Manga manga, final Context context) {
		MalDatabaseAdapter dbAdapter = new MalDatabaseAdapter(context);
		final boolean status = dbAdapter.hasManga(manga.getId());
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		LayoutInflater inflater = LayoutInflater.from(context);
		View viewInflate = inflater.inflate(R.layout.dialog_edit_manga, null);
		final Calendar calendar = Calendar.getInstance();

		final Spinner spinnerStatus = (Spinner) viewInflate.findViewById(R.id.spinner_status);
		final Spinner spinnerScore = (Spinner) viewInflate.findViewById(R.id.spinner_score);
		final Spinner spinnerStartDays = (Spinner) viewInflate.findViewById(R.id.spinner_start_days);
		final Spinner spinnerStartMonth = (Spinner) viewInflate.findViewById(R.id.spinner_start_month);
		final Spinner spinnerStartYear = (Spinner) viewInflate.findViewById(R.id.spinner_start_year);
		final Spinner spinnerFinishDays = (Spinner) viewInflate.findViewById(R.id.spinner_finish_days);
		final Spinner spinnerFinishMonth = (Spinner) viewInflate.findViewById(R.id.spinner_finish_month);
		final Spinner spinnerFinishYear = (Spinner) viewInflate.findViewById(R.id.spinner_finish_year);
		final Spinner spinnerPriority = (Spinner) viewInflate.findViewById(R.id.spinner_priority);
		final EditText editVolumeRead = (EditText) viewInflate.findViewById(R.id.edit_volumes_read);
		final EditText editChapterRead = (EditText) viewInflate.findViewById(R.id.edit_chapters_read);
		final TextView textTitle = (TextView) viewInflate.findViewById(R.id.text_title);
		final CheckBox checkBoxUnknownStartDate = (CheckBox) viewInflate.findViewById(R.id.checkbox_unknown_date_start_date);
		final CheckBox checkBoxInsertStartDate = (CheckBox) viewInflate.findViewById(R.id.checkbox_insert_today_date_start_date);
		final CheckBox checkBoxUnknownFinishDate = (CheckBox) viewInflate.findViewById(R.id.checkbox_unknown_date_finish_date);
		final CheckBox checkBoxInsertFinishDate = (CheckBox) viewInflate.findViewById(R.id.checkbox_insert_today_date_finish_date);
		final EditText editTags = (EditText) viewInflate.findViewById(R.id.edit_tags);
		final EditText editComments = (EditText) viewInflate.findViewById(R.id.edit_comments);

		checkBoxUnknownStartDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							spinnerStartDays.setEnabled(false);
							spinnerStartDays.setSelection(0);

							spinnerStartMonth.setEnabled(false);
							spinnerStartMonth.setSelection(0);

							spinnerStartYear.setEnabled(false);
							spinnerStartYear.setSelection(0);

							checkBoxInsertStartDate.setChecked(false);

						}
					}
				});

		checkBoxInsertStartDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							int day = calendar.get(Calendar.DAY_OF_MONTH);
							int month = calendar.get(Calendar.MONTH);

							spinnerStartDays.setEnabled(true);
							spinnerStartMonth.setEnabled(true);
							spinnerStartYear.setEnabled(true);

							spinnerStartDays.setSelection(day);
							spinnerStartMonth.setSelection(month + 1);
							spinnerStartYear.setSelection(1);

							checkBoxUnknownStartDate.setChecked(false);
						}
					}
				});

		checkBoxUnknownFinishDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							spinnerFinishDays.setEnabled(false);
							spinnerFinishDays.setSelection(0);

							spinnerFinishMonth.setEnabled(false);
							spinnerFinishMonth.setSelection(0);

							spinnerFinishYear.setEnabled(false);
							spinnerFinishYear.setSelection(0);

							checkBoxInsertFinishDate.setChecked(false);

						}
					}
				});

		checkBoxInsertFinishDate
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							int day = calendar.get(Calendar.DAY_OF_MONTH);
							int month = calendar.get(Calendar.MONTH);

							spinnerFinishDays.setEnabled(true);
							spinnerFinishMonth.setEnabled(true);
							spinnerFinishYear.setEnabled(true);

							spinnerFinishDays.setSelection(day);
							spinnerFinishMonth.setSelection(month + 1);
							spinnerFinishYear.setSelection(1);

							checkBoxUnknownFinishDate.setChecked(false);
						}
					}
				});

		ArrayAdapter<SpinnerValue> mAdapterYears = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterYears
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		int year = calendar.get(Calendar.YEAR);
		mAdapterYears.add(new SpinnerValue("Years", "0"));
		for (int a = 0; a <= 3; a++) {
			mAdapterYears.add(new SpinnerValue(String.valueOf(year - a), String
					.valueOf(year - a)));
		}

		spinnerFinishYear.setAdapter(mAdapterYears);
		spinnerStartYear.setAdapter(mAdapterYears);

		ArrayAdapter<SpinnerValue> mAdapterMonth = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterMonth
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		mAdapterMonth.add(new SpinnerValue("Month", "0"));
		mAdapterMonth.add(new SpinnerValue("January", "01"));
		mAdapterMonth.add(new SpinnerValue("Febuary", "02"));
		mAdapterMonth.add(new SpinnerValue("March", "03"));
		mAdapterMonth.add(new SpinnerValue("April", "04"));
		mAdapterMonth.add(new SpinnerValue("May", "05"));
		mAdapterMonth.add(new SpinnerValue("June", "06"));
		mAdapterMonth.add(new SpinnerValue("July", "07"));
		mAdapterMonth.add(new SpinnerValue("August", "08"));
		mAdapterMonth.add(new SpinnerValue("September", "09"));
		mAdapterMonth.add(new SpinnerValue("October", "10"));
		mAdapterMonth.add(new SpinnerValue("November", "11"));
		mAdapterMonth.add(new SpinnerValue("December", "12"));

		spinnerFinishMonth.setAdapter(mAdapterMonth);
		spinnerStartMonth.setAdapter(mAdapterMonth);

		ArrayAdapter<SpinnerValue> mAdapterDays = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		mAdapterDays
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		mAdapterDays.add(new SpinnerValue("Days", "0"));
		for(int a = 1; a <= 9; a++) {
			mAdapterDays.add(new SpinnerValue("0" + String.valueOf(a), "0" + String
					.valueOf(a)));
		}
		for(int a = 10; a <= days; a++) {
			mAdapterDays.add(new SpinnerValue(String.valueOf(a), String
					.valueOf(a)));
		}

		spinnerFinishDays.setAdapter(mAdapterDays);
		spinnerStartDays.setAdapter(mAdapterDays);

		ArrayAdapter<SpinnerValue> adapterScore = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterScore
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterScore.add(new SpinnerValue("Select score", "0"));
		adapterScore.add(new SpinnerValue("10 - Masterpiece", "10"));
		adapterScore.add(new SpinnerValue("9 - Great", "9"));
		adapterScore.add(new SpinnerValue("8 - Very Good", "8"));
		adapterScore.add(new SpinnerValue("7 - Good", "7"));
		adapterScore.add(new SpinnerValue("6 - Fine", "6"));
		adapterScore.add(new SpinnerValue("5 - Average", "5"));
		adapterScore.add(new SpinnerValue("4 - Bad", "4"));
		adapterScore.add(new SpinnerValue("3 - Very Bad", "3"));
		adapterScore.add(new SpinnerValue("2 - Horrible", "2"));
		adapterScore.add(new SpinnerValue("1 - Appalling", "1"));

		spinnerScore.setAdapter(adapterScore);
		if (manga.getScore() == null || manga.getScore().equalsIgnoreCase("0")) {
			spinnerScore.setSelection(0);
		} else { 
			spinnerScore.setSelection(11 - Integer.parseInt(manga.getScore()));
		}

		ArrayAdapter<SpinnerValue> adapterStatus = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterStatus
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterStatus.add(new SpinnerValue("Reading", "reading"));
		adapterStatus.add(new SpinnerValue("Completed", "completed"));
		adapterStatus.add(new SpinnerValue("On-hold", "onhold"));
		adapterStatus.add(new SpinnerValue("Plan to Read", "plantoread"));
		adapterStatus.add(new SpinnerValue("Dropped", "dropped"));
		
		ArrayAdapter<SpinnerValue> adapterPriority = new ArrayAdapter<SpinnerValue>(
				context, android.R.layout.simple_spinner_item);
		adapterPriority
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		adapterPriority.add(new SpinnerValue("Low", "0"));
		adapterPriority.add(new SpinnerValue("Medium", "1"));
		adapterPriority.add(new SpinnerValue("High", "2"));
		
		spinnerPriority.setAdapter(adapterPriority);

		spinnerStatus.setAdapter(adapterStatus);
		if (manga.getReadStatus() != null) {
			if (manga.getReadStatus().equalsIgnoreCase("reading")) {
				spinnerStatus.setSelection(0);
			}
			if (manga.getReadStatus().equalsIgnoreCase("completed")) {
				spinnerStatus.setSelection(1);
			}
			if (manga.getReadStatus().equalsIgnoreCase("onhold")) {
				spinnerStatus.setSelection(2);
			}
			if (manga.getReadStatus().equalsIgnoreCase("plantoread")) {
				spinnerStatus.setSelection(3);
			}
			if (manga.getReadStatus().equalsIgnoreCase("dropped")) {
				spinnerStatus.setSelection(4);
			}
		}

		spinnerStatus.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if(position == 1) {
					editChapterRead.setText(manga.getChapters());
					editVolumeRead.setText(manga.getVolumes());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		textTitle.setText(manga.getTitle());
		if (manga.getVolumesRead() != null) {
			editVolumeRead.setText(manga.getVolumesRead());
		}
		if (manga.getChapterRead() != null) {
			editChapterRead.setText(manga.getChapterRead());
		}
		if (manga.getComments() != null) {
			editComments.setText(manga.getComments());
		}
		if (manga.getTags() != null) {
			editTags.setText(manga.getTags());
		}
		
		if(manga.getPriority() != null) {
			spinnerPriority.setSelection(Integer.parseInt(manga.getPriority()));
		} else {
			spinnerPriority.setSelection(0);
		}

		try {
			Date date = new Date();
			Calendar calendar2 = Calendar.getInstance();
			if (manga.getStartDate() != null) {
				date = DateUtils.parseDate(manga.getStartDate());
				calendar2.setTime(date);
				
				spinnerStartDays.setSelection(calendar2.get(Calendar.DATE));
				spinnerStartMonth.setSelection(calendar2.get(Calendar.MONTH));
				int position = (calendar.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR)) + 1;
				spinnerStartYear.setSelection(position);
			}

			if (manga.getEndDate() != null) {
				date = DateUtils.parseDate(manga.getStartDate());
				calendar2.setTime(date);
				
				spinnerFinishDays.setSelection(calendar2.get(Calendar.DATE));
				spinnerFinishMonth.setSelection(calendar2.get(Calendar.MONTH));
				int position = (calendar.get(Calendar.YEAR) - calendar2.get(Calendar.YEAR)) + 1;
				spinnerFinishYear.setSelection(position);
			}
		} catch (DateParseException e) {
			e.printStackTrace();
		}

		builder.setView(viewInflate)
				.setPositiveButton(status == true ? "Update" : "Add",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								manga.setPriority(((SpinnerValue) spinnerPriority
										.getSelectedItem()).getValue());
								manga.setReadStatus(((SpinnerValue) spinnerStatus
										.getSelectedItem()).getValue());
								manga.setVolumesRead(editVolumeRead.getText().toString());
								manga.setChapterRead(editChapterRead.getText().toString());
								manga.setScore(((SpinnerValue) spinnerScore
										.getSelectedItem()).getValue());
								manga.setTags(editTags.getText().toString());
								manga.setComments(editComments.getText().toString());
								if (checkBoxUnknownStartDate.isChecked() == false
										&& spinnerStartMonth
												.getSelectedItemPosition() != 0
										&& spinnerStartDays
												.getSelectedItemPosition() != 0
										&& spinnerStartYear
												.getSelectedItemPosition() != 0) {

									try {
										String month = ((SpinnerValue) spinnerStartMonth
												.getSelectedItem()).getValue();
										String date = ((SpinnerValue) spinnerStartDays
												.getSelectedItem()).getValue();
										String year = ((SpinnerValue) spinnerStartYear
												.getSelectedItem()).getName();

										Date parseDate = DateUtils.parseDate(
												month + date + year,
												new String[] { "MMddyyyy" });

										manga.setStartDate(DateUtils.formatDate(
												parseDate, "MMddyyyy"));
										
									} catch (DateParseException e) {
										manga.setStartDate("null");
										e.printStackTrace();
									}

								} else {
									manga.setStartDate("null");
								}
								if (checkBoxUnknownFinishDate.isChecked() == false
										&& spinnerFinishMonth
												.getSelectedItemPosition() != 0
										&& spinnerFinishDays
												.getSelectedItemPosition() != 0
										&& spinnerFinishYear
												.getSelectedItemPosition() != 0) {

									try {
										String month = ((SpinnerValue) spinnerFinishMonth
												.getSelectedItem()).getValue();
										String date = ((SpinnerValue) spinnerFinishDays
												.getSelectedItem()).getValue();
										String year = ((SpinnerValue) spinnerFinishYear
												.getSelectedItem()).getName();

										Date parseDate = DateUtils.parseDate(
												month + date + year,
												new String[] { "MMddyyyy" });

										manga.setEndDate(DateUtils.formatDate(
												parseDate, "MMddyyyy"));
									} catch (DateParseException e) {
										manga.setEndDate("null");
										e.printStackTrace();
									}

								} else {
									manga.setEndDate("null");
								}

								final Manga[] params = { manga };
								new MangaUtil().new RequestMangaUpdate(context, status)
										.execute(params);
							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		builder.create();
		builder.show();
	}
	
	public class RequestMangaUpdate extends AsyncTask<Manga, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		private MalDatabaseAdapter dbAdapter;
		private boolean status;

		public RequestMangaUpdate(Context context, boolean status) {
			dialog = new ProgressDialog(context);
			dbAdapter = new MalDatabaseAdapter(context);
			
			this.context = context;
			this.status = status;
		}

		@Override
		protected Boolean doInBackground(Manga... params) {
			boolean response = false; 
			if(status == true) {
				try {
					response = ConnectionUtil.postUpdateXML(null, params[0],
						context, ConnectionUtil.API_HOST_UPDATE_MANGA);
				} catch (IOException e) {
					response = false;
					e.printStackTrace();
				}
			} else {
				try {
					response = ConnectionUtil.postAddXML(null, params[0],
						context, ConnectionUtil.API_HOST_ADD_MANGA);
				} catch (IOException e) {
					response = false;
					e.printStackTrace();
				}
			}
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			History history = new History();
			history.setAnimeId("");
			history.setDescription(WordUtils.capitalize(params[0].getReadStatus()) + " - " + 
					params[0].getChapterRead() + " of " + params[0].getChapters() + " chapter");
			history.setMangaId(params[0].getId());
			history.setTitle(params[0].getTitle() + " - " + params[0].getType());
			history.setType("manga");
			history.setUpdateDate(format.format(new Date()));
			
			if (response == true && status == true) {
				dbAdapter.updateMangaWithPriority(params[0]);
				if(dbAdapter.hasHistory(history) == true) {
					dbAdapter.updateHistory(history);
				} else {
					dbAdapter.insertHistory(history, params[0].getImageUrl());
				}
			}
			if (response == true && status == false) {
				dbAdapter.saveManga(params[0]);
				dbAdapter.insertHistory(history, params[0].getImageUrl());
			}
			
			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result == true) {
				if(status == true) {
					Toast.makeText(context, context.getResources().getString(R.string.success_update),
						Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(context, context.getResources().getString(R.string.success_add),
							Toast.LENGTH_LONG).show();
				}
			} else {
				if(status == true) {
					Toast.makeText(context, context.getResources().getString(R.string.failed_update),
						Toast.LENGTH_LONG).show();
					
				} else {
					Toast.makeText(context, context.getResources().getString(R.string.failed_add),
							Toast.LENGTH_LONG).show();
				}
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("Loading Data ...");
			dialog.show();
		}
	}
	
	public class RequestMangaDelete extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog dialog;
		private MalDatabaseAdapter dbAdapter;
		private Context context;

		public RequestMangaDelete(Context context) {
			dialog = new ProgressDialog(context);
			dbAdapter = new MalDatabaseAdapter(context);
			this.context = context;
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean response = false;
			try {
				response = ConnectionUtil.postDeleteXML(
						ConnectionUtil.API_HOST + "api/mangalist/delete/"
								+ params[0] + ".xml", context);
				
				if (response == true) {
					dbAdapter.deleteManga(params[0]);
				}
				
			} catch (ClientProtocolException e) {
				response = false; 
				e.printStackTrace();
			} catch (IOException e) {
				response = false;
				e.printStackTrace();
			}
			
			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			dialog.dismiss();
			if (result) {
				Toast.makeText(context, context.getResources().getString(R.string.success_remove),
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(context, context.getResources().getString(R.string.failed_remove), Toast.LENGTH_LONG)
						.show();
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("Loading Data ...");
			dialog.show();
		}
	}
}
